package indigo.control
{
	import indigo.errors.IndigoError;
	import indigo.utils.IDisposable;

	import flash.events.Event;
	import flash.utils.Dictionary;

	/**
	 * @author Patrick
	 */
	public class ApplicationController implements IDisposable
	{
		/**
		 * Reference to the FrontController
		 */
		private static var INSTANCE:ApplicationController = null;
		private var _commandList:Dictionary;


		/**
		 * Constructor
		 * 
		 */
		public function ApplicationController( singleton:SingletonEnforcer )
		{
			super();
			log( "Instantiating" );
			initialize();
		}


		private function initialize():void
		{
			_commandList = new Dictionary( true );
		}


		public function addNotification( notification:String, command:Class ):void
		{
			if ( _commandList[ notification ] )
			{
				throw new IndigoError( IndigoError.INDIGO_EVENT_ALREADY_ADDED );
			}

			log( "Adding notification: '" + notification + "'" );

			_commandList[ notification ] = command;
			NotificationCenter.getInstance().addEventListener( notification, onNotification );
		}


		private function onNotification( notice:IndigoNotice ):void
		{
			var CommandDefinition:Class = _commandList[ notice.type ] as Class;
			if ( CommandDefinition != null )
			{
				log( "Received notification: '" + notice.type + "'" );
				log( "Executing command: '" + CommandDefinition + "'" );

				var myCommand:Command = new CommandDefinition();
				myCommand.execute( notice );
			}
		}


		/**
		 * Returns the instance of the FrontController. When there is no reference it
		 * will create a new instance.
		 * @return	Instance of the ModelLocator
		 * 
		 */
		public static function getInstance():ApplicationController
		{
			if ( INSTANCE == null )
				INSTANCE = new ApplicationController( new SingletonEnforcer );

			return INSTANCE;
		}


		/**
		 * @inheritDoc
		 * 
		 */
		public function dispose( event:Event = null ):void
		{
			INSTANCE = null;
			_commandList = null;
		}
	}
}
internal class SingletonEnforcer
{
}